package cn.doctor.assistant.pad.ui.hudong;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.doctor.assistant.pad.MyApplication;
import cn.doctor.assistant.pad.MyApplication.MessageEventListener;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.base.BaseFragment;
import cn.doctor.assistant.pad.db.ConversationDBManager;
import cn.doctor.assistant.pad.entity.ContactInfo;
import cn.doctor.assistant.pad.im.adapter.ChatAllHistoryAdapter;
import cn.doctor.assistant.pad.im.model.InviteMessgeDao;

/**
 * Created by jiaolf on 2016/3/28.
 * 互动-联系人-会话
 */
public class ChatHistoryFragment extends BaseFragment implements MessageEventListener {

    View rootView;
    @InjectView(R.id.msgCenterListView)
    ListView listView;
    @InjectView(R.id.empty)
    LinearLayout emptyView;

    ChatAllHistoryAdapter adapter;
    private List<EMConversation> conversationList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.f_msg_page, container, false);
        ButterKnife.inject(this, rootView);
        MyApplication.getInstance().addMsgEventListener(this);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    // XXX 重新显示的时候，刷新一下
    @Override
    public void onRedisplay() {
        super.onRedisplay();
        refrushUI();
    }

    void initialize() {
        adapter = new ChatAllHistoryAdapter(getActivity(), 1, conversationList);
        listView.setAdapter(adapter);
        listView.setVerticalScrollBarEnabled(false);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation emContact = adapter.getItem(position);
                //UnreadCountDBManager.getInstance().updateUnreadCount(emContact.getUserName(), 0);
                ContactInfo user = MyApplication.getInstance().getContact(emContact.getUserName());
                MyApplication.getInstance().onSelectedContactChanged(user);
            }
        });

        registerForContextMenu(listView);
        refrushUI();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(Menu.NONE, R.id.delete_message, Menu.NONE, "删除会话");
    }

    @Override
    public void onResume() {
        super.onResume();
        refrushUI();
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.delete_message) {
            int position = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
            EMConversation tobeDeleteCons = adapter.getItem(position);
            // 删除此会话(最后一个参数：是否同时删除聊天记录，设置为false)
            EMChatManager.getInstance().deleteConversation(tobeDeleteCons.getUserName(),
                    tobeDeleteCons.isGroup(), false);
            InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
            inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName());
            adapter.remove(tobeDeleteCons);
            adapter.notifyDataSetChanged();

            //TODO 更新消息未读数
            //
            emptyView.setVisibility(conversationList.isEmpty() ? View.VISIBLE : View.GONE);
            return true;
        }

        return super.onContextItemSelected(item);
    }

    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        EMChatManager.getInstance().loadAllConversations();

        // Hashtable<String, EMConversation> conversations =
        // EMChatManager.getInstance().getAllConversations();
        Hashtable<String, EMConversation> conversations = new Hashtable<>();

        ArrayList<String> realConverstList = ConversationDBManager.getInstance().getConversationList();
        for (String username : realConverstList) {
            // 不显示转发给医生的消息
            if(username.equals(MyApplication.getInstance().mCurrDoctor.getLogin_name())) continue;

            EMConversation conv = EMChatManager.getInstance().getConversation(username);
            if (conv != null) {
                conversations.put(username, conv);
            }
        }

        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                // UI.showToast("会话列表："+conversation.getUserName());
                if (conversation.getAllMessages().size() != 0) {
                    // 过滤掉admin推送的消息
                    if (conversation.getUserName().equals("admin")) {
                        continue;
                    }
                    sortList.add(
                            new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    private void refrushUI() {
        conversationList.clear();
        conversationList.addAll(loadConversationsWithRecentChat());
        if (adapter != null)
            adapter.notifyDataSetChanged();
        emptyView.setVisibility(conversationList.isEmpty() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void refrush(EMNotifierEvent.Event eventType, EMMessage message) {
        if (eventType == EMNotifierEvent.Event.EventNewMessage) {
            refrushUI();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        MyApplication.getInstance().removeMsgEventListener(this);
    }
}
